package hangler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-hubs/cache"
	"novel-hubs/models"
	"novel-hubs/pkg"
	"time"
)

func User(c *gin.Context) {
	name := c.PostForm("name")
	password := c.PostForm("password")
	var user models.User
	redis_key := "user" + name
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次 禁止登录",
		})
		return
	}
	err := models.DB.Where("name = ?", name).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "未找到该用户",
		})
		return
	}
	if pkg.Md5Password(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if cacheData >= 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次以上 登录封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return

}

func List(c *gin.Context) {
	var posts []models.Posts
	redis_key := "list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		models.DB.Find(&posts)
		marshal, _ := json.Marshal(posts)
		cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &posts)
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": posts,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var posts models.Posts
	redis_key := "detail" + id
	cache.Rdb.Get(cache.Ctx, redis_key)
	models.DB.Where("id = ?", id).Find(&posts)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "进入详情成功",
		"data": posts,
	})
}

func Add(c *gin.Context) {
	name := c.PostForm("name")

	var user models.User
	err := models.DB.Where("name = ?", name).Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
	})
	return
}
